<%@ page import="com.weaver.general.BaseBean" %>
<%@ page import="org.apache.axis.encoding.Base64" %>
<%@ page import="org.apache.commons.codec.digest.DigestUtils" %>
<%@ page import="org.apache.http.HttpEntity" %>
<%@ page import="org.apache.http.client.methods.CloseableHttpResponse" %>
<%@ page import="org.apache.http.client.methods.HttpPost" %>
<%@ page import="org.apache.http.config.Registry" %>
<%@ page import="org.apache.http.config.RegistryBuilder" %>
<%@ page import="org.apache.http.conn.socket.ConnectionSocketFactory" %>
<%@ page import="org.apache.http.conn.socket.PlainConnectionSocketFactory" %>
<%@ page import="org.apache.http.conn.ssl.SSLConnectionSocketFactory" %>
<%@ page import="org.apache.http.entity.StringEntity" %>
<%@ page import="org.apache.http.impl.client.CloseableHttpClient" %>
<%@ page import="org.apache.http.impl.client.HttpClients" %>
<%@ page import="org.apache.http.impl.conn.PoolingHttpClientConnectionManager" %>
<%@ page import="org.apache.http.util.EntityUtils" %>
<%@ page import="weaver.common.DateUtil" %>
<%@ page import="javax.net.ssl.SSLContext" %>
<%@ page import="javax.net.ssl.TrustManager" %>
<%@ page import="javax.net.ssl.X509TrustManager" %>
<%@ page import="java.io.IOException" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="static weaver.interfaces.cese.duss.ceseutil.ImageUtil.getContent" %>
<%@ page import="static weaver.interfaces.cese.duss.ceseutil.ImageUtil.getImagefilename" %>
<%@ page import="static weaver.interfaces.cese.duss.ceseutil.ImageUtil.*" %>
<%@ page import="java.util.Map" %>
<%@ page language="java" contentType="text/html; charset=utf-8" %>
<jsp:useBean id="rs" class="weaver.conn.RecordSet" scope="page"/>
<jsp:useBean id="bb" class="weaver.general.BaseBean"/>
<%
    out.print( "--------WeaImageUploadCronJob---------" );
    String result = sendAttachment(42696, "CLBX-2021-0897", "00020", "1005397");
    out.print( "result:"+result );
%>
</script>
<%!
    //发送附件
    public static String sendAttachment(int [] fileIds,String djbh,String hszz,String uploadUser){
        com.weaver.general.BaseBean baseBean = new com.weaver.general.BaseBean();
        String img_API_KEY = baseBean.getPropValue("langchao","IMG_API_KEY");
        String img_url =  baseBean.getPropValue("langchao","img_url");
        Map<String, Object> params = new HashMap<>();
        String clientcode = "WB";//调用系统代码
        String servicecode = "ImageCenter";//提供服务的系统编码
        String date = DateUtil.getFullDate().substring( 0, 10 ).replaceAll( "-", "" );
        String time = date + DateUtil.getFullDate().substring( 11, 19 ).replaceAll( ":", "" );//明文参数验证时，该节点必输，格式为：YYYYMMDDHHmmSS
        String ticket = time + servicecode + clientcode + img_API_KEY;//明文参数验证时，该节点必输，取值为：time值+ servicecode 值+ clientcode 值+约定KEY，生成的MD5值
        String md5Ticket = DigestUtils.md5Hex( ticket );
        String servername = "sendImage";//调用的服务标记
        String servertype = "";//调用的服务类型，0/实时接口，1/定时接口，影像系统可配置，默认取影像系统配置
        params.put( "clientcode", clientcode );
        params.put( "servicecode", servicecode );
        params.put( "time", time );
        params.put( "ticket", md5Ticket );
        params.put( "servername", servername );
        params.put( "servertype", servertype );
        String str = "param=";
        for(int i=1;i<=fileIds.length;i++){
           int fileId = fileIds[i];
            String barcode = djbh;//单据编码或者合同号
            String filename = getImagefilename(fileId);//文件名（包括扩展名称）
            String content = Base64.encode(getContent(fileId));//图片或pdf序列化后的Base64值
            String compoanycode = hszz;//单位编号
            String useraccount = uploadUser;//上传用户
            String page = String.valueOf(i);//当前页数
            String totalpage = String.valueOf(fileIds.length);//总记录
            params.put( "serviceid", i );
            params.put( "barcode", barcode );
            params.put( "filename", filename );
            params.put( "content", content );
            params.put( "compoanycode", compoanycode );
            params.put( "useraccount", useraccount );
            params.put( "ifhx", 0 );
            params.put( "page", page );
            params.put( "totalpage", totalpage );
            String param = XMLContent( params );
            String str = "param=" + param;
            baseBean.writeLog("str:"+str);
        }

        Map<String,String> headers = new HashMap<>(  );
        headers.put("Content-Type","application/x-www-form-urlencoded");
        String returns = httpPostRaw(img_url,str,headers,"UTF-8");
        returns = returns.replaceAll("&lt;","<").replaceAll( "&gt;",">" );
        baseBean.writeLog("returns:"+returns);
        return returns;
    }
    //发生HTTP请求post
    public static String httpPostRaw(String url,String stringJson,Map<String,String> headers, String encode){
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog( "-------------发送post请求----------" );
        baseBean.writeLog( "-------------url----------"+url );
        baseBean.writeLog( "-------------stringJson----------"+stringJson );
        baseBean.writeLog( "-------------headers----------"+headers );
        baseBean.writeLog( "-------------encode----------"+encode );
        if(encode == null){
            encode = "utf-8";
        }
        String content = null;
        CloseableHttpResponse httpResponse = null;
        CloseableHttpClient closeableHttpClient = null;
        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            X509TrustManager trustManager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(
                        java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                        String paramString) {
                }

                @Override
                public void checkServerTrusted(
                        java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                        String paramString) {
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            sslcontext.init(null, new TrustManager[] { trustManager }, null);
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslcontext)).build();
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

            //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
            closeableHttpClient = HttpClients.createDefault();
            HttpPost httpost = new HttpPost(url);

            //设置header
            httpost.setHeader("Content-type", "application/json");
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpost.setHeader(entry.getKey(),entry.getValue());
                }
            }
            //组织请求参数
            StringEntity stringEntity = new StringEntity(stringJson, encode);
            httpost.setEntity(stringEntity);

            //响应信息
            httpResponse = closeableHttpClient.execute(httpost);
            int code = httpResponse.getStatusLine().getStatusCode();
            baseBean.writeLog( "接口响应状态码："+code );
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {  //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
    //组装XML
%>